package com.zrfintech.api.controller;

import com.alibaba.fastjson.JSONObject;
import com.zrfintech.common.util.HttpRequestUtil;
import com.zrfintech.common.util.HttpResponseUtil;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * BaseController
 * 
 * @author v_tangyuanliang
 *
 */
@Controller
public class BaseController {
    /** 日志. */
    private static final Logger LOGGER = LoggerFactory.getLogger(BaseController.class);

    protected HttpServletRequest getRequest() {
        return ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
    }

    /**
     * 得到客户端IP地址
     * 
     * @return
     */
    protected String getRemoteIP() {
        return HttpRequestUtil.getRemoteRealIpAddr(getRequest());
    }

    /**
     * 获取项目路径
     * 
     * @return
     */
    protected String getRootPath() {
        return getRequest().getSession().getServletContext().getRealPath("/");
    }

    /**
     * 获取请求内容
     * 
     * @return
     * @throws Exception
     */
    protected String getContent() throws Exception {
        HttpServletRequest request = getRequest();
        String method = request.getMethod().toUpperCase();
        String content = "";
        if (RequestMethod.GET.toString().equals(method)) {
            content = request.getQueryString();
        } else if (RequestMethod.POST.toString().equals(method)) {
            content = IOUtils.toString(request.getReader());
        } else {
            throw new Exception();
        }
        LOGGER.info("method={}, content={}", method, content);
        if (StringUtils.isEmpty(content)) {
            throw new Exception();
        }
        return content;
    }

    /**
     * 输出对象客户端
     * 
     * @param data 输出的数据对象
     * @throws IOException
     */
    protected void print(Object data, HttpServletResponse response) {
        print(JSONObject.toJSONString(data), response);
    }

    /**
     * 输出String客户端
     * 
     * @param data 输出的数据对象
     * @throws IOException
     */
    private void print(String data, HttpServletResponse response) {
        if (null == data) {
            LOGGER.warn("data is null");
            data = "";
        }
        LOGGER.info("result is " + data);
        HttpResponseUtil.renderText(response, data);
    }
}